"use strict";
cc._RF.push(module, '52041UgyPBI+aXxIUfwGUEW', 'GbzLevel');
// scripts/game/GbzLevel.ts

"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var GbzEnum_1 = require("../GbzEnum");
var GbzInstance_1 = require("../GbzInstance");
var GbzUtils_1 = require("../GbzUtils");
var GbzAudioManager_1 = require("../manager/GbzAudioManager");
var GbzDataManager_1 = require("../manager/GbzDataManager");
var GbzPoolManager_1 = require("../manager/GbzPoolManager");
var GbzResManager_1 = require("../manager/GbzResManager");
var GbzSdkManager_1 = require("../manager/GbzSdkManager");
var GbzToastManager_1 = require("../manager/GbzToastManager");
var GbzBoard_1 = require("./GbzBoard");
var GbzBox_1 = require("./GbzBox");
var GbzScrew_1 = require("./GbzScrew");
var GbzTarget_1 = require("./GbzTarget");
// carolsail
var _a = cc._decorator, ccclass = _a.ccclass, property = _a.property;
var GbzLevel = /** @class */ (function (_super) {
    __extends(GbzLevel, _super);
    function GbzLevel() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.rootBoxes = null;
        _this.rootBoards = null;
        _this.targets = null;
        _this.screws = [];
        _this.boards = [];
        _this.boxDataArr = [];
        _this.screwRefreshArr = [];
        return _this;
    }
    GbzLevel.prototype.init = function () {
        var _this = this;
        this.node.height = cc.winSize.height;
        this.rootBoxes = this.node.getChildByName('root_boxes');
        this.rootBoards = this.node.getChildByName('root_boards');
        this.targets = this.node.getChildByName('targets');
        var json = GbzResManager_1.default.ins.json("gbz_level" + GbzDataManager_1.default.ins.game_level_current);
        var levelData = JSON.parse(JSON.stringify(json));
        if (levelData.groupData.length) {
            this.initData(levelData);
        }
        this.rootBoards.children.forEach(function (group) {
            group.active = true;
            var groupName = group.name;
            group.children.forEach(function (tempBoard) {
                tempBoard.active = false;
                var boardIndex = GbzUtils_1.getNumFromStr(tempBoard.name);
                var boardItem = GbzPoolManager_1.default.ins.getNode('GbzBoardItem', group);
                boardItem.getChildByName('screws').zIndex = 5;
                var board = GbzPoolManager_1.default.ins.getNode("GbzBoard" + boardIndex, boardItem, cc.v3(tempBoard.x, tempBoard.y));
                board.angle = tempBoard.angle;
                board.group = groupName;
                board.getComponent(cc.PhysicsCollider).apply();
                var screws = boardItem.getChildByName('screws');
                var boardComp = board.getComponent(GbzBoard_1.default);
                var joints = boardComp.getJoints();
                joints.forEach(function (joint) {
                    if (joint.node.active) {
                        var group_1 = joint.node.group;
                        var groupDataArr = levelData['boards'][group_1];
                        if (groupDataArr && groupDataArr.length) {
                            var anchor = joint.anchor;
                            var pos = GbzUtils_1.toXY(joint.node, screws, anchor);
                            var screw = GbzPoolManager_1.default.ins.getNode('GbzScrew', screws, cc.v3(pos.x, pos.y));
                            var screwComp = screw.getComponent(GbzScrew_1.default);
                            var randomIndex = GbzUtils_1.random(0, groupDataArr.length - 1);
                            var groudData = groupDataArr[randomIndex];
                            groupDataArr.splice(randomIndex, 1);
                            screwComp.init(groudData, group_1, joint);
                            joint.connectedBody = screw.getComponent(cc.RigidBody);
                            _this.screws.push(screw);
                        }
                    }
                });
                _this.boards.push(board);
            });
        });
        // this.rootBoards.children.forEach(gboard => {
        // gboard.children.forEach(item => {
        //     const item1 = item.children[0]
        //     const item2 = item.children[1]
        //     let board = item1
        //     let screws = item2
        //     if (item2.getComponent(cc.RigidBody)) {
        //         board = item2
        //         screws = item1
        //     }
        //     board.group = gboard.name
        //     board.getComponent(cc.PhysicsCollider).apply()
        //     const boardComp = board.getComponent(GbzBoard)
        //     const joints = boardComp.getJoints()
        //     joints.forEach(joint => {
        //         if (joint.node.active) {
        //             const group = joint.node.group
        //             const groupDataArr = levelData['boards'][group]
        //             if (groupDataArr && groupDataArr.length) {
        //                 const anchor = joint.anchor
        //                 const pos = toXY(joint.node, screws, anchor)
        //                 const screw = GbzPoolManager.ins.getNode('GbzScrew', screws, cc.v3(pos.x, pos.y))
        //                 const screwComp = screw.getComponent(GbzScrew)
        //                 const randomIndex = random(0, groupDataArr.length - 1)
        //                 const groudData = groupDataArr[randomIndex]
        //                 groupDataArr.splice(randomIndex, 1)
        //                 screwComp.init(groudData, group, joint)
        //                 joint.connectedBody = screw.getComponent(cc.RigidBody)
        //                 this.screws.push(screw)
        //             }
        //         }
        //     })
        //     this.boards.push(board)
        // })
        // })
        this.boxDataArr = levelData['boxes'];
        this.rootBoxes.children.forEach(function (box) {
            var lock = box.getChildByName('lock');
            if (lock) {
                if (!lock.hasEventListener('click'))
                    lock.on('click', _this.onBoxLockClick, _this);
            }
            else {
                var boxComp = box.getComponent(GbzBox_1.default);
                var index = _this.boxDataArr.shift();
                boxComp.refresh(index);
            }
        });
        if (!this.node.hasEventListener('touchstart'))
            this.node.on('touchstart', this.onTouchStart, this);
    };
    GbzLevel.prototype.initData = function (data) {
        var nums = 0;
        for (var i = 0; i < data['groupData'].length; i++) {
            nums += data['groupData'][i];
        }
        var boxArr = [];
        for (var i = 0; i < Math.floor(nums / 3); i++) {
            boxArr.push(GbzUtils_1.random(1, 7));
        }
        var boardArr = [];
        for (var i = 0; i < boxArr.length; i++) {
            var box = boxArr[i];
            boardArr.push(box, box, box);
        }
        data['boxes'] = boxArr;
        for (var i = 0; i < data['groupData'].length; i++) {
            var num = data['groupData'][i];
            var arr = [];
            for (var j = 0; j < num; j++) {
                var rand = GbzUtils_1.random(1, 2);
                var v = rand == 1 ? boardArr.pop() : boardArr.shift();
                arr.push(v);
            }
            data['boards']["g" + (i + 1)] = arr;
        }
    };
    GbzLevel.prototype.testData = function () {
        var json = GbzResManager_1.default.ins.json("gbz_level" + GbzDataManager_1.default.ins.game_level_current);
        var data = [];
        for (var key in json.boards) {
            data.push.apply(data, json.boards[key]);
        }
        var obj1 = GbzUtils_1.countGameLevelData(data);
        var obj2 = GbzUtils_1.countGameLevelData(json.boxes);
        console.log(obj1, obj2);
    };
    GbzLevel.prototype.onTouchStart = function (e) {
        var _this = this;
        if (GbzDataManager_1.default.ins.status == GbzEnum_1.ENUM_STATUS.UNRUN)
            return;
        var location = e.getLocation();
        if (GbzDataManager_1.default.ins.isSkill) {
            if (GbzDataManager_1.default.ins.skillIndex !== 2)
                return;
            var targetBoard_1 = null;
            for (var i = this.boards.length - 1; i >= 0; i--) {
                var board = this.boards[i];
                var point = board.convertToNodeSpaceAR(location);
                var points = board.getComponent(cc.PolygonCollider).points;
                var isInter = cc.Intersection.pointInPolygon(point, points);
                if (isInter) {
                    targetBoard_1 = board;
                    break;
                }
            }
            if (targetBoard_1) {
                GbzAudioManager_1.default.ins.play(GbzEnum_1.ENUM_CLIP.SKILL_REMOVE);
                cc.tween(targetBoard_1).to(0.2, { scale: 0 }).call(function () {
                    GbzDataManager_1.default.ins.isSkill = false;
                    _this.onBoardDestroy(targetBoard_1);
                }).start();
            }
        }
        else {
            var targetScrew = null;
            for (var i = this.screws.length - 1; i >= 0; i--) {
                var screw = this.screws[i];
                var point = screw.convertToNodeSpaceAR(location);
                var points = screw.getComponent(cc.PolygonCollider).points;
                var isInter = cc.Intersection.pointInPolygon(point, points);
                if (isInter) {
                    targetScrew = screw;
                    break;
                }
            }
            if (targetScrew) {
                var bool = this.checkScrewMove(targetScrew);
                if (bool) {
                    GbzAudioManager_1.default.ins.play(GbzEnum_1.ENUM_CLIP.SCREW_OUT);
                    this.checkScrewMoveTo(targetScrew);
                }
                else {
                    GbzAudioManager_1.default.ins.play(GbzEnum_1.ENUM_CLIP.SCREW_EMPTY);
                }
            }
        }
    };
    GbzLevel.prototype.onScrewDestroy = function (node) {
        var index = this.screws.findIndex(function (screw) { return screw == node; });
        if (index >= 0)
            this.screws.splice(index, 1);
        node.removeFromParent(true);
    };
    GbzLevel.prototype.onBoardDestroy = function (node) {
        var index = this.boards.findIndex(function (board) { return board == node; });
        if (index >= 0)
            this.boards.splice(index, 1);
        node.removeFromParent(true);
    };
    GbzLevel.prototype.checkScrewMove = function (node) {
        var bool = true;
        var screwComp = node.getComponent(GbzScrew_1.default);
        var screwGroupIndex = GbzUtils_1.getNumFromStr(screwComp.group);
        for (var i = 0; i < this.boards.length; i++) {
            var board = this.boards[i];
            var pos = GbzUtils_1.toXY(node, board);
            var points = board.getComponent(cc.PolygonCollider).points;
            var isInter = cc.Intersection.polygonCircle(points, { position: pos, radius: node.width / 2 });
            if (isInter) {
                var boardGroupIndex = GbzUtils_1.getNumFromStr(board.group);
                if (screwGroupIndex > boardGroupIndex) {
                    bool = false;
                    break;
                }
            }
        }
        return bool;
    };
    GbzLevel.prototype.checkScrewMoveTo = function (node) {
        var _this = this;
        var screwComp = node.getComponent(GbzScrew_1.default);
        var boxComp = null;
        for (var i = 0; i < this.rootBoxes.children.length; i++) {
            var box = this.rootBoxes.children[i];
            var bcomp = box.getComponent(GbzBox_1.default);
            if (bcomp.isActive() && bcomp.index == screwComp.index) {
                boxComp = bcomp;
                break;
            }
        }
        if (boxComp) {
            var screwTarget_1 = boxComp.getScrewCurrent();
            if (screwTarget_1) {
                var screwMoveNode = GbzPoolManager_1.default.ins.getNode('GbzScrewMove', this.node);
                var start = GbzUtils_1.toXY(node, screwMoveNode.parent);
                var end = GbzUtils_1.toXY(screwTarget_1, screwMoveNode.parent);
                this.onScrewDestroy(node);
                boxComp.addScrewNum();
                this.onScrewMove(screwMoveNode, screwComp.index, start, end, function () {
                    GbzAudioManager_1.default.ins.play(GbzEnum_1.ENUM_CLIP.SCREW_IN);
                    screwTarget_1.active = true;
                    var isFull = boxComp.checkFull();
                    if (isFull) {
                        _this.onBoxRefresh(boxComp.node);
                    }
                });
            }
        }
        else {
            var targetComp_1 = this.targets.getComponent(GbzTarget_1.default);
            if (targetComp_1.isActive()) {
                var screwTarget_2 = targetComp_1.getScrewCurrent();
                if (screwTarget_2) {
                    var screwMoveNode = GbzPoolManager_1.default.ins.getNode('GbzScrewMove', this.node);
                    var start = GbzUtils_1.toXY(node, screwMoveNode.parent);
                    var end = GbzUtils_1.toXY(screwTarget_2, screwMoveNode.parent);
                    this.onScrewDestroy(node);
                    targetComp_1.pushScrew(screwComp.index);
                    this.onScrewMove(screwMoveNode, screwComp.index, start, end, function () {
                        screwTarget_2.active = true;
                        targetComp_1.addScrew(screwComp.index, screwTarget_2);
                        var isFull = targetComp_1.checkFull();
                        if (isFull)
                            GbzInstance_1.default.gameMgr.onGameOver(GbzEnum_1.ENUM_UI.LAYER_LOSE_FULL);
                    });
                }
            }
            else {
                GbzAudioManager_1.default.ins.play(GbzEnum_1.ENUM_CLIP.SCREW_EMPTY);
            }
        }
    };
    GbzLevel.prototype.onTargetToBox = function (box) {
        var _this = this;
        var boxComp = box.getComponent(GbzBox_1.default);
        var targetComp = this.targets.getComponent(GbzTarget_1.default);
        var targetScrews = targetComp.getScrews();
        var _loop_1 = function (i) {
            var screw = targetScrews[i];
            var index = GbzUtils_1.getNumFromStr((screw.getComponent(cc.Sprite).spriteFrame)._name);
            if (boxComp.index == index) {
                if (boxComp.screwNum <= boxComp.screwNumMax - 1) {
                    var screwTarget_3 = boxComp.getScrewCurrent();
                    if (screwTarget_3) {
                        var screwMoveNode = GbzPoolManager_1.default.ins.getNode('GbzScrewMove', this_1.node);
                        var start = GbzUtils_1.toXY(screw, screwMoveNode.parent);
                        var end = GbzUtils_1.toXY(screwTarget_3, screwMoveNode.parent);
                        targetComp.clearOne(screw);
                        boxComp.addScrewNum();
                        this_1.onScrewMove(screwMoveNode, index, start, end, function () {
                            GbzAudioManager_1.default.ins.play(GbzEnum_1.ENUM_CLIP.SCREW_IN);
                            screwTarget_3.active = true;
                            var isFull = boxComp.checkFull();
                            if (isFull) {
                                _this.onBoxRefresh(boxComp.node);
                            }
                        });
                    }
                }
            }
        };
        var this_1 = this;
        for (var i = 0; i < targetScrews.length; i++) {
            _loop_1(i);
        }
    };
    GbzLevel.prototype.onScrewMove = function (node, index, start, end, cb) {
        node.getComponent(cc.Sprite).spriteFrame = GbzResManager_1.default.ins.sprite("gbz_screw" + index);
        node.setPosition(start);
        node.active = true;
        var moveDis = GbzUtils_1.getDistance(start, end);
        var moveSpeed = 3000;
        var moveTime = moveDis / moveSpeed;
        cc.tween(node).to(moveTime, { position: cc.v3(end.x, end.y) }).call(function () {
            node.removeFromParent(true);
            cb && cb();
        }).start();
    };
    GbzLevel.prototype.getTargetLock = function () {
        var comp = this.targets.getComponent(GbzTarget_1.default);
        return comp.getLock();
    };
    GbzLevel.prototype.hasTargetScew = function () {
        var comp = this.targets.getComponent(GbzTarget_1.default);
        return comp.hasScrew();
    };
    GbzLevel.prototype.getTargetScrews = function () {
        var comp = this.targets.getComponent(GbzTarget_1.default);
        return comp.getScrews();
    };
    GbzLevel.prototype.onTargetClear = function () {
        var comp = this.targets.getComponent(GbzTarget_1.default);
        comp.clearAll();
    };
    GbzLevel.prototype.checkTargetFull = function () {
        var targetComp = this.targets.getComponent(GbzTarget_1.default);
        return targetComp.checkFull();
    };
    GbzLevel.prototype.onTargetLockDestroy = function (node) {
        var comp = this.targets.getComponent(GbzTarget_1.default);
        comp.addUnlockNum();
        node.removeFromParent(true);
    };
    GbzLevel.prototype.onBoxLockClick = function (e) {
        var _this = this;
        if (GbzDataManager_1.default.ins.status == GbzEnum_1.ENUM_STATUS.UNRUN)
            return;
        GbzSdkManager_1.default.ins.showVideo(function () { return __awaiter(_this, void 0, void 0, function () {
            var lock;
            return __generator(this, function (_a) {
                GbzAudioManager_1.default.ins.play(GbzEnum_1.ENUM_CLIP.SKILL_UNLOCK);
                lock = e.node;
                this.onBoxRefresh(lock.parent);
                return [2 /*return*/];
            });
        }); }, function (msg) {
            GbzToastManager_1.default.ins.show(msg, { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) });
        });
    };
    GbzLevel.prototype.onBoxRefresh = function (box) {
        var _this = this;
        var boxComp = box.getComponent(GbzBox_1.default);
        if (this.boxDataArr.length) {
            var boxIndex = this.boxDataArr[0];
            var res_1 = GbzUtils_1.takeValueFromArray(this.screwRefreshArr, boxIndex);
            if (res_1.length >= boxComp.screwNumMax)
                this.boxDataArr.shift();
            cc.tween(box).to(0.2, { scale: 0 }).call(function () {
                var index = _this.boxDataArr.shift();
                boxComp.unlock();
                boxComp.setScrewNum(res_1.length);
                boxComp.refresh(index);
            }).to(0.2, { scale: 1 }).call(function () {
                _this.onTargetToBox(box);
            }).start();
        }
        else {
            cc.tween(box).to(0.2, { scale: 0 }).call(function () {
                boxComp.unlock();
                if (_this.checkBoxClear()) {
                    GbzInstance_1.default.gameMgr.onGameOver(GbzEnum_1.ENUM_UI.LAYER_WIN);
                }
            }).start();
        }
    };
    GbzLevel.prototype.checkBoxClear = function () {
        var count = 0;
        this.rootBoxes.children.forEach(function (box) {
            var boxComp = box.getComponent(GbzBox_1.default);
            if (boxComp.isActive()) {
                count += 1;
            }
        });
        return count <= 0;
    };
    GbzLevel = __decorate([
        ccclass
    ], GbzLevel);
    return GbzLevel;
}(cc.Component));
exports.default = GbzLevel;

cc._RF.pop();